//
//  PlayChatViewController.m
//  Runner
//
//  Created by 小二同學 on 2020/3/31.
//  Copyright © 2020 The Chromium Authors. All rights reserved.
//

#import "PlayChatViewController.h"
#import "PlayChatCell.h"
#import <SocketRocket/SRWebSocket.h>

@interface PlayChatViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,SRWebSocketDelegate>

/**
 UITableView 基类
 */
@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic,strong) NSDictionary *palyInfo;
@property (nonatomic,strong) UIView *bottomView;
@property (nonatomic,strong) UITextField *field;

@property (strong,nonatomic) SRWebSocket* srwebsocket;

@property (strong,nonatomic) AFHTTPSessionManager *mgr;
@property (nonatomic,strong) NSDictionary *data;
@property (nonatomic, copy) NSString *from_client_id;

@property (nonatomic,strong) NSTimer *timer;
@end

@implementation PlayChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(getMessage) userInfo:nil repeats:YES];
    [self getChatList];
}

- (void)viewDidDisappear:(BOOL)animated {
    [self.timer invalidate];
    self.timer = nil;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHideOrShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHideOrShow:) name:UIKeyboardWillHideNotification object:nil];
    
    [self scrollTableToFoot:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_field resignFirstResponder];
}

- (void)sendPlayInfo:(NSDictionary *)dic {
    _palyInfo = [NSDictionary dictionaryWithDictionary:dic];
}

#pragma mark - 获取直播消息
- (void)getChatList {
           
    AFHTTPSessionManager *manager = [self getManager];

    NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"TOKEN"];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setValue:token forKey:@"access_token"];

    [manager POST:[NSString stringWithFormat:@"%@v1/token/change",API_URL] parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        self.data = dic[@"data"];
        if ([dic[@"data"] isKindOfClass:[NSDictionary class]]) {
            //jychat.ahjtest.top ws://jychat.xinanyun.cn
            
            [self getMessage];
//            NSURL *url = [NSURL URLWithString:CHAT_URL];
//            self.srwebsocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:url]];
//            self.srwebsocket.delegate = self;
//            [self.srwebsocket open];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
}

- (void)getMessage {
    AFHTTPSessionManager *manager = [self getManager];

    NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"TOKEN"];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setValue:token forKey:@"token"];
    [params setValue:_palyInfo[@"id"] forKey:@"liveId"];

    [manager POST:[NSString stringWithFormat:@"%@v1/live/getChatInfo",API_URL] parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        self.data = dic[@"data"];
        if ([dic[@"data"] isKindOfClass:[NSArray class]]) {
            //jychat.ahjtest.top ws://jychat.xinanyun.cn
            self.dataSource = [NSMutableArray arrayWithArray:dic[@"data"]];
            [self.tableView reloadData];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
}

//webSocket连接成功
-(void)webSocketDidOpen:(SRWebSocket *)srWebSocket{
    [self.srwebsocket send:[self dictionaryToJson:@{@"type":@"login", @"uid":self.data[@"id"], @"client_name":self.data[@"nickname"], @"live_id":_palyInfo[@"id"]}]];
    [self.srwebsocket send:[self dictionaryToJson:@{@"type":@"say",@"from_uid":self.data[@"id"], @"to_client_id":@"all", @"avatar":self.data[@"avatar"]}]];
}

//webSocket连接失败
-(void)webSocket:(SRWebSocket *)srWebSocket didFailWithError:(NSError *)error{
    
     NSLog(@"error%@",error);
}
//webSocket收到服务器发过来的消息
-(void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message{
    NSLog(@"收到服务器发过来%@",message);
        
    NSDictionary *dic = [self dictionaryWithJsonString:message];
    
    NSLog(@"%@",dic);
    NSString *type = dic[@"type"];
    
    NSLog(@"%@",type);
    
    if ([dic[@"type"] isEqualToString:@"say"]||[dic[@"type"] isEqualToString:@"login"]) {
         [self.dataSource addObject:dic];
        [self.tableView reloadData];
    }else if ([(NSString *)dic[@"type"] isEqualToString:@"init"]){
        self.from_client_id = dic[@"client_id"];
    }
}

//字典转json格式字符串：
- (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];

    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

- (void)keyboardHideOrShow:(NSNotification *)notification {
    NSString *notificationName = notification.name;     //获取通知名称
    NSDictionary *keyboardInfo = notification.userInfo;//获取通知内容
    CGRect keyboardFrame = [keyboardInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    [UIView animateWithDuration:0.3f animations:^{
        self.bottomView.frame = CGRectMake(0.0f, [UIScreen mainScreen].bounds.size.height - keyboardFrame.size.height - GK_SAFEAREA_BTM - 94 - ([UIScreen mainScreen].bounds.size.width * 9/16), self.view.frame.size.width, 50);
        self.tableView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - keyboardFrame.size.height - GK_SAFEAREA_BTM - 94 - ([UIScreen mainScreen].bounds.size.width * 9/16));
    }];
    
    if ([notificationName isEqualToString:UIKeyboardWillHideNotification]) {
        //键盘将要消失
        self.bottomView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 44 - ([UIScreen mainScreen].bounds.size.width * 9/16) - GK_SAFEAREA_BTM - 50, [UIScreen mainScreen].bounds.size.width, 50);
        self.tableView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 44 - ([UIScreen mainScreen].bounds.size.width * 9/16) - GK_SAFEAREA_BTM - 50);
    }
    else {
        //键盘将要弹起
    }
    
    [self scrollTableToFoot:NO];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if ([self.data isKindOfClass:[NSDictionary class]]) {
        if (_field.text.length <= 0) {
            return YES;
        }
        
//        [self.srwebsocket send:[self dictionaryToJson:@{@"type":@"say",@"uid":self.data[@"id"], @"to_client_id":@"all",@"to_client_name":@"所有人", @"content":_field.text,@"live_id":_palyInfo[@"id"]}]];
        
        AFHTTPSessionManager *manager = [self getManager];

        NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"TOKEN"];
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        [params setValue:token forKey:@"token"];
        [params setValue:_palyInfo[@"id"] forKey:@"liveId"];
        [params setValue:_field.text forKey:@"content"];

        [manager POST:[NSString stringWithFormat:@"%@v1/live/saveLiveChat",API_URL] parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

            [self getMessage];

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        }];
        
        self.field.text = @"";
        [self scrollTableToFoot:NO];
        [self.field resignFirstResponder];
        
    }
    
    
    return YES;
}

- (void)sendAction {
    if (_field.text.length <= 0) {
        return;
    }
    
//    [self.srwebsocket send:[self dictionaryToJson:@{@"type":@"say",@"uid":self.data[@"id"], @"to_client_id":@"all",@"to_client_name":@"所有人", @"content":_field.text,@"live_id":_palyInfo[@"id"]}]];
    AFHTTPSessionManager *manager = [self getManager];

    NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"TOKEN"];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setValue:token forKey:@"token"];
    [params setValue:_palyInfo[@"id"] forKey:@"liveId"];
    [params setValue:_field.text forKey:@"content"];

    [manager POST:[NSString stringWithFormat:@"%@v1/live/saveLiveChat",API_URL] parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        [self getMessage];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
    self.field.text = @"";
    [self scrollTableToFoot:NO];
    [self.field resignFirstResponder];
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *ID = @"PlayChatCell";
    PlayChatCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[PlayChatCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (self.dataSource.count > 0) {
        [cell sendChatInfo:self.dataSource[indexPath.row]];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [_field resignFirstResponder];
}

#pragma make - 表头
- (UIView *)kTableHeaderView {

    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, 60)];
    UIView *lightView = [[UIView alloc] initWithFrame:CGRectZero];
    lightView.layer.masksToBounds = YES;
    lightView.backgroundColor = UIColorFromRGB(0xfff5f5f5);
    lightView.layer.cornerRadius = 17;
    [bgView addSubview:lightView];
    [lightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(bgView);
        make.width.mas_equalTo(170);
        make.height.mas_equalTo(30);
    }];
    UIView *view = [[UIView alloc] init];
    view.layer.masksToBounds = YES;
    view.backgroundColor = UIColorFromRGB(0xff149AFD);
    view.layer.cornerRadius = 3;
    [lightView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lightView).offset(20);
        make.width.height.mas_equalTo(6);
        make.centerY.equalTo(lightView);
    }];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    label.text = [NSString stringWithFormat:@"共有%@人参与直播",_palyInfo[@"countUser"]];
    label.font = [UIFont systemFontOfSize:13];
    label.textColor = UIColorFromRGB(0xff919699);
    [lightView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view.mas_right).offset(8);
        make.centerY.equalTo(lightView);
    }];
    return bgView;
}


- (void)scrollTableToFoot:(BOOL)animated {
    NSInteger s = [self.tableView numberOfSections];
    if (s<1) return;
    NSInteger r = [self.tableView numberOfRowsInSection:s-1];
    if (r<1) return;

    NSIndexPath *ip = [NSIndexPath indexPathForRow:self.dataSource.count - 1 inSection:0];

    [self.tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionBottom animated:animated];
}

#pragma mark - setter getter
- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 50 - ([UIScreen mainScreen].bounds.size.width * 9/16) - GK_SAFEAREA_BTM - 44, [UIScreen mainScreen].bounds.size.width, 50)];
        _bottomView.backgroundColor = UIColorFromRGB(0xfff5f5f5);
        
        _field = [[UITextField alloc] initWithFrame:CGRectMake(20, 10, [UIScreen mainScreen].bounds.size.width - 40 , 30)];
        _field.delegate = self;
        _field.layer.masksToBounds = YES;
        _field.layer.cornerRadius = 12;
        _field.returnKeyType = UIReturnKeySend;
        _field.placeholder = @"发个消息和主播互动吧";
        _field.backgroundColor = [UIColor clearColor];
        [_bottomView addSubview:_field];
        
        UIButton *sendButton = [[UIButton alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 100, 10, 80, 30)];
        sendButton.backgroundColor = UIColorFromRGB(0xff1296db);
        [sendButton setTitle:@"发送" forState:UIControlStateNormal];
        [sendButton addTarget:self action:@selector(sendAction) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:sendButton];
    }
    return _bottomView;
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        NSMutableArray *dataSource = [NSMutableArray array];
        _dataSource = dataSource;
    }
    return _dataSource;
}

- (UITableView *)tableView{
    
    if (!_tableView) {
        
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 44 - ([UIScreen mainScreen].bounds.size.width * 9/16) - GK_SAFEAREA_BTM - 50) style:UITableViewStylePlain];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.showsVerticalScrollIndicator = NO;
        tableView.showsHorizontalScrollIndicator = NO;
        tableView.dataSource = self;
        tableView.translatesAutoresizingMaskIntoConstraints = NO;
        tableView.backgroundColor = [UIColor whiteColor];
        tableView.delegate = self;
        tableView.estimatedRowHeight = 40;
        tableView.rowHeight = UITableViewAutomaticDimension;
        tableView.tableFooterView = [[UIView alloc] init];
        tableView.tableHeaderView = [self kTableHeaderView];

        _tableView = tableView;
    }
    return _tableView;
}

- (AFHTTPSessionManager *)getManager
{
    _mgr = [AFHTTPSessionManager manager];
    [_mgr.requestSerializer setTimeoutInterval:10];
    _mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    _mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/javascript",@"text/html",@"text/plain",nil];
    _mgr.requestSerializer = [AFJSONRequestSerializer serializer];
    _mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    return _mgr;
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
- (void)dealloc {
    [self.timer invalidate];
    self.timer = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
